<template>
  <div class="login">
    <div class="login-box">
      <div class="login_viwe_logo">
        <img class="login_view_Img" :src="assetsSource.loginPagePic" v-if="assetsSource.loginPagePic" />
        <img class="login_view_Img" src="../../assets/imgs/login_view_Img1.png" v-else />
        <img class="login_logo" src="../../assets/imgs/logo@2x.png" />
      </div>
      <a-form layout="horizontal" autoComplete="off" :model="formState" @submit.prevent="userRepetLogin">
        <div class="classified_text" v-if="assetsSource.isEnableReinsurance">{{ assetsSource.secretSysTitle }}</div>
        <a-form-item :name="['username', 'value']" :label="formState.username.label" :rules="[formState.username.rule]">
          <a-input v-model:value="formState.username.value" size="large" placeholder="请输入用户名">
            <template #prefix>
              <i class="iconfont">&#xe925;</i>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item :name="['password', 'value']" :label="formState.password.label" :rules="[formState.password.rule]">
          <a-input-password v-model:value="formState.password.value" size="large" type="password" placeholder="请输入密码">
            <template #prefix>
              <i class="iconfont">&#xe8ce;</i>
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item v-if="isShowCode" :name="['verifyCode', 'value']" :label="formState.verifyCode.label"
          :rules="[formState.verifyCode.rule]">
          <a-input v-model:value="formState.verifyCode.value" placeholder="验证码" :maxlength="4" size="large">
            <template #prefix>
              <SafetyOutlined />
            </template>
            <template #suffix>
              <img :src="captchaImg" style="height: 24px" class="absolute right-0 h-full cursor-pointer"
                @click="setCaptcha" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item style="margin-bottom: 0;">
          <a-button type="primary" html-type="submit" size="large" :loading="formState.loading" block>
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
    <modifyPassword :isVisible="ispasswordVisible" @handleOk="handleOk" @handleCancle="handleCancle"
      v-if="ispasswordVisible"></modifyPassword>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, createVNode } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message, Modal } from "ant-design-vue";
import { useUserStore } from "@/store/modules/user";
import { useDynamicRouting } from "@/store/modules/dynamicRouting";
import request from "@/api/index";
import modifyPassword from "@/layouts/modifyPassword.vue";
import { LOGIN_NAME } from "@/router/constant";
import { useTabsViewStore } from "@/store/modules/tabsView";
import { useKeepAliveStore } from "@/store/modules/keepAlive";
import { encrypt3DES } from "@/utils/cryptojs";
import { Storage } from "@/utils/Storage";
import router from '@/router';
import { modeProp } from "@/type.d";
import msgModal from "@/components/modal/modelConfig/MsGModal";
//type
interface dataSourceType {
  [propName: string]: any;
}

//data
let modAlProps: modeProp = reactive({
  width: "M",
  title: "新建",
});
const isVisible = ref<boolean>(false);
const buttons = ref<dataSourceType[]>([
  {
    text: "确定",
    "html-type": "submit",
    keepAlive: true,
  },
]);
const captchaImg = ref<string>("");
const isShowCode = ref<boolean>(false);
const ispasswordVisible = ref(false);
const keepAliveStore = useKeepAliveStore();
const classified = ref<any>({});
const formState = reactive<dataSourceType>({
  username: {
    value: "",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "用户名不能为空！",
    },
    label: "",
  },
  password: {
    value: "",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "密码不能为空！",
    },
    label: "",
  },
  verifyCode: {
    value: "",
    rule: {
      required: true,
      trigger: ["change", "blur"],
      message: "验证码不能为空！",
    },
    label: "",
  },
  loading: false,
});

const route = useRoute();
const router1 = useRouter();
const tabsViewStore = useTabsViewStore();
const userStore = useUserStore();
const assetsSource = ref<dataSourceType>({}) //静态资源文件
const setCaptcha = async () => {
  const data = (await request.fetchVerificationCode({})) || {};
  captchaImg.value = data?.imageBase64Str;
  isShowCode.value = captchaImg.value ? true : false;
};

const handleOk = async () => {
  ispasswordVisible.value = false;
  formState.password.value = ''
};

// 取消个人中心弹窗、
const handleCancle = () => {
  ispasswordVisible.value = false;
};

const userRepetLogin = () => {
  request.userRepetLogin({userName: formState.username.value}).then((res: any) => {
    console.log(res);
    if(res) {
      Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "账号已在其他设备登录，是否继续？",
      content: "",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
        
      }),
      okText: "继续",
      onOk: () => {
        Modal.destroyAll();
        handleSubmit()
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
    }else {
      handleSubmit()
    }
    
  })
};

const handleSubmit =  () => {
  if (formState.username.value.trim() == "" || formState.password.value.trim() == "") {
    return message.warning("用户名或密码不能为空！");
  }
  message.loading('登录中...', 0);
  formState.loading = true;
  const postData = {
    code: formState.verifyCode.value,
    desStr: encrypt3DES(formState.password.value),
    //desStr: await request.fetchEncryptPwd({ pwd: formState.password.value }),
    identity: formState.username.value,
  };
   request
    .fetchDoLogin(postData)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        userStore.setUser(Object.assign(res.data, assetsSource.value));
        localStorage.userInfo = JSON.stringify(res.data);
        Storage.set("isLogin", false)
        tabsViewStore.closeAllTabs();
        if (res.data.isNeedChangePwd) {
          ispasswordVisible.value = true;
          return
        }
        router1.replace("/workplace/index")

      } else {
        if (res.data.failType === 4) {
          setCaptcha();
        }
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });

  formState.loading = false;
  message.destroy();
};
const getImgs = () => {
  request
    .loginPageSetUp()
    .then((res: any) => {
      console.log(res)
      if (res.code = '00000 00000') {
        classified.value = res
        assetsSource.value = res;
        userStore.setUser(assetsSource.value);
        loginWithCode();
      }

    })
}
const loginWithCode = () => {
  request
    .loginWithCode()
    .then((res: any) => {
      isShowCode.value = res;
      if (isShowCode.value) {
        setCaptcha();
      }
    })

}
onMounted(() => {
  localStorage.clear();
  sessionStorage.clear();
  getImgs();
})
</script>

<style lang="less" scoped>
.login {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("../../assets/imgs/loginB.png") center repeat;
  // background-size: 100%;

  .login-box {
    display: flex;
    width: 920px;
    height: 506px;
    align-items: center;
    background: #fff;
    border-radius: 4px;
    overflow: hidden;
    .classified_text {
      font-size: 20px;
      color: #262626;
      margin-bottom: 40px;
      line-height: 20px;
    }

    .login_viwe_logo {
      display: flex;
      align-items: center;
      position: relative;
      height: 506px;
      width: 344px;
      justify-content: center;
      margin-right: 56px;
      overflow: hidden;

      .svg-icon {
        font-size: 48px;
      }

      .login_view_Img {
        width: auto;
        height: 100%;

      }

      .login_logo {
        position: absolute;
        top: 184px;
        width: 179px;
        height: auto;
      }
    }

    :deep(.ant-form) {
      width: 464px;

      .ant-col {
        width: 100%;
      }

      .ant-form-item-label {
        padding-right: 6px;
      }
    }

    .ant-form-item {
      margin-bottom: 40px;
    }

    .ant-form-item-control-input {
      height: 48px;
    }

    .iconfont {
      color: rgba(0, 0, 0, 0.6);
      font-size: 17px;
    }
  }

  :deep(.ant-input-prefix) {
    margin-right: 14px;
  }
}
</style>
